/**
 * Copyright (c) 2014- 2015 YCY Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.jkwzms.system.permission.web.controller;

import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Sets;
import com.jkwzms.common.Constants;
import com.jkwzms.common.entity.enums.AvailableEnum;
import com.jkwzms.common.entity.search.SearchOperator;
import com.jkwzms.common.entity.search.Searchable;
import com.jkwzms.common.inject.annotation.BaseComponent;
import com.jkwzms.common.utils.EasyUiMsg;
import com.jkwzms.common.web.controller.BaseCRUDController;
import com.jkwzms.system.permission.entity.Role;
import com.jkwzms.system.permission.entity.RoleResourcePermission;
import com.jkwzms.system.permission.service.PermissionService;
import com.jkwzms.system.permission.service.RoleService;

/**
 * <p>
 * User: Jack Liang
 * <p>
 * Date: 13-1-28 下午4:29
 * <p>
 * Version:1.0.0
 */
@Controller
@RequestMapping(value = "/sys/permission/role")
public class RoleController extends BaseCRUDController<Role, Long> {

    @Autowired
    @BaseComponent
    private RoleService       roleService;

    @Autowired
    private PermissionService permissionService;

    @Override
    protected void setCommonData(Model model) {
        super.setCommonData(model);
        model.addAttribute("availableList", AvailableEnum.values());

        Searchable searchable = Searchable.newSearchable();
        searchable.addSearchFilter("show", SearchOperator.eq, true);
        model.addAttribute("permissions", permissionService.findAllWithNoPageNoSort(searchable));
    }

    /**
     * to list page
     * 
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "main")
    public String main() {
        return "sys/permission/role/list";
    }

    @RequestMapping(value = "create/discard", method = RequestMethod.POST)
    @Override
    public Map<String, Object> create(Model model, @Valid @ModelAttribute("m") Role m, BindingResult result,
                                      RedirectAttributes redirectAttributes) {
        throw new RuntimeException("discarded method");
    }

    @RequestMapping(value = "{id}/update/discard", method = RequestMethod.POST)
    @Override
    public String update(Model model, @Valid @ModelAttribute("m") Role m, BindingResult result,
                         @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
                         RedirectAttributes redirectAttributes) {

        throw new RuntimeException("discarded method");
    }

    /**
     * 添加角色信息
     * 
     * @param model
     * @param role
     * @param result
     * @param resourceIds
     * @param permissionIds
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public Map<String, Object> createWithResourcePermission(Model model, @Valid @ModelAttribute("m") Role role,
                                                            BindingResult result,
                                                            @RequestParam("resourceId") Long[] resourceIds,
                                                            @RequestParam("permissionIds") Long[][] permissionIds,
                                                            RedirectAttributes redirectAttributes) {

        fillResourcePermission(role, resourceIds, permissionIds);

        return super.create(model, role, result, redirectAttributes);
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateWithResourcePermission(Model model, @Valid @ModelAttribute("m") Role role,
                                                            BindingResult result,
                                                            @RequestParam("resourceId") Long[] resourceIds,
                                                            @RequestParam("permissionIds") Long[][] permissionIds) {

        fillResourcePermission(role, resourceIds, permissionIds);
        if (hasError(role, result)) {
            EasyUiMsg.successMsg(Boolean.FALSE);
        }
        baseService.update(role);
        return EasyUiMsg.successMsg(Boolean.TRUE);
    }

    private void fillResourcePermission(Role role, Long[] resourceIds, Long[][] permissionIds) {
        int resourceLength = resourceIds.length;

        if (resourceIds.length == 0) {
            return;
        }

        if (resourceLength == 1) { // 如果长度为1 那么permissionIds就变成如[[0],[1],[2]]这种
            Set<Long> permissionIdSet = Sets.newHashSet();
            for (Long[] permissionId : permissionIds) {
                permissionIdSet.add(permissionId[0]);
            }
            role.addResourcePermission(new RoleResourcePermission(resourceIds[0], permissionIdSet));

        } else {
            for (int i = 0; i < resourceLength; i++) {
                role.addResourcePermission(new RoleResourcePermission(resourceIds[i], Sets.newHashSet(permissionIds[i])));
            }
        }

    }

    @RequestMapping(value = "/changeStatus/{newStatus}")
    public String changeStatus(HttpServletRequest request, @PathVariable("newStatus") Boolean newStatus,
                               @RequestParam("ids") Long[] ids, RedirectAttributes redirectAttributes) {

        this.permissionList.assertHasUpdatePermission();

        for (Long id : ids) {
            Role role = roleService.findOne(id);
            role.setShow(newStatus);
            roleService.update(role);
        }

        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "操作成功！");

        return "redirect:" + request.getAttribute(Constants.BACK_URL);
    }

    @RequestMapping("{role}/permissions")
    public String permissions(@PathVariable("role") Role role) {
        return viewName("permissionsTable");
    }

    /**
     * 获取role by Id
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "get", method = RequestMethod.POST)
    @ResponseBody
    public Role getRoleById(@RequestParam("id") Long id) {
        return this.roleService.findOne(id);
    }

    /**
     * 打开资源树
     * 
     * @return
     */
    @RequestMapping(value = "resourceTree", method = RequestMethod.GET)
    public String resourceTree() {
        return viewName("resourceTree");
    }

}
